package com.gopay.scheduler.service.AutoGenTrade.impl;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.cps.dao.order.CpsGeneralPayOrderQueryDAO;
import com.gopay.common.datasource.DBType;
import com.gopay.common.datasource.DbContextHolder;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.report.ReportConsoleTransQuery;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.ReflectionUtil;
import com.gopay.cron.web.util.DicTranslate;
import com.gopay.scheduler.dao.AutoGenTradeRecordDao;
import com.gopay.scheduler.job.vo.OptimizedTransQueryVO;
import com.gopay.scheduler.service.AutoGenTrade.AutoGenTradeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository("autoGenTradeService")
public class AutoGenTradeServiceImpl  implements AutoGenTradeService{

	@Resource(name = "autoGenTradeRecordDao")
    private AutoGenTradeRecordDao autoGenTradeRecordDao;
    @Resource(name = "cpsGenPayOrderQueryDAO")
    private CpsGeneralPayOrderQueryDAO cpsGenPayOrderQueryDAO;

    @Resource(name = "cpsGeneralMainOrderQueryDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public List<OptimizedTransQueryVO> getDataList(String beginDate,String endDate,int pageIndex,int pageSize) {
		//查询参数
        Map<String, Object> map=new HashMap<String, Object>();
        OptimizedTransQueryVO paramVo=new OptimizedTransQueryVO();
        //modify by liuxuyang 20171213 更改交易记录下载查询条件 start
        paramVo.setOrderStlmTmBegin(beginDate);
        paramVo.setOrderStlmTmEnd(endDate);
//        paramVo.setGopayTxnTmBegin(beginDate);
//        paramVo.setGopayTxnTmEnd(endDate);
        //modify by liuxuyang 20171213 更改交易记录下载查询条件 end
        //封装查询Hql
        String hql = buildQueryHql(paramVo,map);
        //排序
        String sortHql=hql+" order by gopayOrderId desc";

        DbContextHolder.setDbType(DBType.DS_REPORT.value);
        //执行查询
        List<ReportConsoleTransQuery> rsList=autoGenTradeRecordDao.findByHql(sortHql, map, pageIndex,pageSize);
        //结果集
        List<OptimizedTransQueryVO> voList=buildResult(rsList);
		return voList;
	}
	/**
	 * 查询总数
	 */
	public int getDataCount(String beginDate,String endDate){
		Map<String, Object> map=new HashMap<String, Object>();
		OptimizedTransQueryVO paramVo=new OptimizedTransQueryVO();
		//modify by liuxuyang 20171213 更改交易记录下载查询条件 start
        paramVo.setOrderStlmTmBegin(beginDate);
        paramVo.setOrderStlmTmEnd(endDate);
//		paramVo.setGopayTxnTmBegin(beginDate);
//        paramVo.setGopayTxnTmEnd(endDate);
        //modify by liuxuyang 20171213 更改交易记录下载查询条件 end
		//封装查询Hql
        String hql = buildQueryHql(paramVo,map); 
        //排序
        String sortHql=hql+" order by gopayOrderId desc";
		//查询总记录数
        String countHql="select count(*) "+hql;
        DbContextHolder.setDbType(DBType.DS_REPORT.value);
		return autoGenTradeRecordDao.findCountByHql(countHql, map);
	}
	private String buildQueryHql(OptimizedTransQueryVO paramVo,Map<String, Object> map){
        StringBuilder sb=new StringBuilder("FROM ReportConsoleTransQuery WHERE 1=1 ");
        
        sb.append(" and txnStaCd =20000 ");
        
        if(StringUtils.isNotBlank(paramVo.getOrderStlmTmBegin())){
            sb.append(" and orderStlmTm >= TO_DATE(:OrderStlmTmBegin, 'YYYY-MM-DD') ");
            map.put("OrderStlmTmBegin", paramVo.getOrderStlmTmBegin());
        }
        if(StringUtils.isNotBlank(paramVo.getOrderStlmTmEnd())){
            sb.append(" and orderStlmTm < TO_DATE(:OrderStlmTmEnd, 'YYYY-MM-DD') ");
            map.put("OrderStlmTmEnd", paramVo.getOrderStlmTmEnd());
        }
        return sb.toString();
    }
	
	/**
     * 封装结果
     * @param rsList
     * @return
     */
    private List<OptimizedTransQueryVO> buildResult(List<ReportConsoleTransQuery> rsList){
        List<OptimizedTransQueryVO> voList=new ArrayList<OptimizedTransQueryVO>();
        OptimizedTransQueryVO vo;
        for(ReportConsoleTransQuery d :rsList){
            vo=new OptimizedTransQueryVO();
            ReflectionUtil.copyProperties(vo, d);
            
            vo.setGopayTxnTmBegin(DateUtils.format(d.getGopayTxnTm(), "yyyy-MM-dd HH:mm:ss"));
            if(d.getOrderStlmTm()!=null){
                vo.setOrderStlmTmBegin(DateUtils.format(d.getOrderStlmTm(), "yyyy-MM-dd HH:mm:ss"));
            }
            
            
            String gopayIntTxnCd = d.getGopayIntTxnCd();
			vo.setTxnCdName(IntTxnCd.getIntTxnCdName(gopayIntTxnCd));//生产bug5期 优化 将DicTranslate 类中的交易码翻译替换为 IntTxnCd中的翻译 lx 2017-6-15 12:27:46
			//add by liuxuyang 添加移动数字证书翻译 20171213 start
            /*if(GatewaySource.GATEWAY_SOURCE_05.value.equals(d.getTerminalSource())){
            	if(IntTxnCd._00601.value.equals(vo.getGopayIntTxnCd())){
            		vo.setTxnCdName("购买数字证书(移动)");
            	} else if (IntTxnCd._00605.value.equals(vo.getGopayIntTxnCd())) {
            		vo.setTxnCdName("数字证书退款(移动)");
            	}
            }*/
            //add by liuxuyang 添加移动数字证书翻译 20171213 end
            //vo.setTxnSts(DicTranslate.translateTranStatus(d.getTxnStaCd()));
            vo.setTxnSts(TxnStaCode.getCategory(d.getTxnStaCd()));
            vo.setPayChannel(DicTranslate.getPayChannelName(d.getPayChannel()));
            vo.setTerminalSource(translateTerminalSource(d.getTerminalSource()));
            vo.setSettleType(translateSettleType(d.getSettleType()));
            String translateHandleSts = translateHandleSts(d.getHandleStaCd());
            if(IntTxnCd._00701.value.equals(gopayIntTxnCd) && StringUtils.isEmpty(translateHandleSts)){
            	translateHandleSts="处理中";
            }
			vo.setHandleStaCd(translateHandleSts);
            vo.setPayAcctProdCd(DicTranslate.getAcctProd(d.getPayAcctProdCd()));
            vo.setRealFeeAmt(d.getRealFeeAmt().subtract(d.getRefundFeeAmt()));
            
            //是否需要补单
            if("00100,00400,00200,00201,00202".indexOf(gopayIntTxnCd)>-1
                    &&TxnStaCode.TXN_STA_CD_20000.value==d.getTxnStaCd()){
                vo.setNotifyOrder(true);
            }
            
            //是否需要对账
            if(StringUtils.isNotBlank(vo.getRecvBankOrderId())&&"01,03,04,06,51,30,31,32,16,17".indexOf(d.getPayChannel())>-1
                    &&TxnStaCode.TXN_STA_CD_20000.value!=d.getTxnStaCd()){
                vo.setCheckOrder(true);
            }
            
            //手续费承担方
            vo.setOrderFeePayer(translateOrderFeePayer(vo.getOrderFeePayer()));
            
            //删除date类型属性
            vo.setCreatedTs(null);
            vo.setLastUpdTs(null);
            vo.setGopayTxnTm(null);
            vo.setOrderStlmTm(null);
            vo.setOldPayChannel(addOldPayChannelInfoToOptimizedTransQueryVO(vo.getGopayOrderId()));
            voList.add(vo);
        }
        return voList;
    }
    
    private String translateTerminalSource(String code){
        String name = "";
        if ("01".equals(code)) {
            name = "PC端";
        } else if ("02".equals(code)) {
            name = "移动端";
        }else if("05".equals(code)){
            name = "国付宝钱包";
        }else if("08".equals(code)){//增加生钱包交易来源 modify by tangyang at 20161118
            name = "生钱包";
        }else if("20".equals(code)){//添加兜兜平台购买天溢盈来源 modify by liuxuyang 20171031
            name = "兜兜平台";
        }
        
        return name;
    }
    
    private String translateSettleType(String code){
        String name = "";
        if ("01".equals(code)) {
            name = "线上（自动）";
        } else if ("02".equals(code)) {
            name = "线上";
        } else if ("03".equals(code)) {
            name = "线下";
        }
        
        return name;
    }
    
    private String translateHandleSts(String code){
        String name = "";
        if ("01".equals(code)) {
            name = "处理中";
        } else if ("02".equals(code)) {
            name = "待审核";
        } else if ("03".equals(code)) {
            name = "待确认";
        } else if ("04".equals(code)) {
            name = "成功";
        }else if ("05".equals(code)) {
            name = "失败";
        }
        
        return name;
    }
    
    private String translateOrderFeePayer(String code) {
        if(code !=null) {
            switch (code) {
            case "00":
                return "不涉及";
            case "01":
                return "付方承担";
            case "02":
                return "收方承担";
            case "03":
                return "平台承担";
            default:
                return "";
            }
        }
        return "";
    }
   /* private String addOldPayChannelInfoToOptimizedTransQueryVO(String gopayOrderId){
        String hql = " select m from CpsGenMainOrder m where m.gopayOrderId = :gopayOrderId ";
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("gopayOrderId",gopayOrderId);
        List<CpsGenMainOrder> mainOrder = cpsGeneralMainOrderQueryDAO.findByHql(hql, map);
        if (!CollectionUtils.isEmpty(mainOrder)) {
        	if(org.apache.commons.lang.StringUtils.isNotBlank(mainOrder.get(0).getRelevanceGopayOrderId())){
                CpsGenMainOrder oldMainOrder = cpsGeneralMainOrderQueryDAO.findByGopayOrderId(mainOrder.get(0).getRelevanceGopayOrderId());
                return oldMainOrder.getPayChannel();
            }
        }
        
        return "";
    }*/

    private String addOldPayChannelInfoToOptimizedTransQueryVO(String gopayOrderId){
        String hql = " select m from CpsGenMainOrder m where m.gopayOrderId = :gopayOrderId ";
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("gopayOrderId",gopayOrderId);
        List<CpsGenMainOrder> mainOrder = cpsGeneralMainOrderQueryDAO.findByHql(hql, map);
        if (!CollectionUtils.isEmpty(mainOrder)) {
            if(org.apache.commons.lang.StringUtils.isNotBlank(mainOrder.get(0).getRelevanceGopayOrderId())){
                CpsGenMainOrder oldMainOrder = cpsGeneralMainOrderQueryDAO.findByGopayOrderId(mainOrder.get(0).getRelevanceGopayOrderId());
                return oldMainOrder.getPayChannel();
            }
        }

        return "";
    }
}
